#! /usr/bin/vim +$
if version >= 500

" pathogen {{{
runtime bundle/vim-pathogen/autoload/pathogen.vim
"当multiple-culsors和autocomplete一起使用时，也会出现问题，于是用下面两行禁止：
let g:pathogen_disabled=[]
call add(g:pathogen_disabled, 'delimitMate')
call add(g:pathogen_disabled, 'vim-orgmode')
call add(g:pathogen_disabled, 'vim-markdown')
execute pathogen#infect()
" call pathogen#infect('textobjs/{}')
set sessionoptions-=options
" }}}

"mapleader指定map中的<leader>按键。
let mapleader='\'

" normal set {{{
"这一条会让粘贴出现问题。
"set fileencodings=utf-8,utf-16,gbk,GB18030,GB2312,big5,ucs-bom,cp936
"这些字符解析的编码，应该按照它们出现的频率进行排序，否则常见的编码被不常见的编码解析，就成了乱七八糟的东西了。
"这种设置居然导致打开fat.h文件乱码，utf-16抢占utf-8的解析权？
"set fileencodings=utf-8,gbk,GB2312,GB18030,big5,ucs-bom,cp936,utf-16,utf-8
set fileencodings=utf-8,gbk,GB2312,GB18030,big5,ucs-bom,cp936,utf-8
" 若为bomb，那么无论对fileencodings怎样设置，打开新文件，将采用utf-8编码。
set nobomb
" set fileencodings=gbk
" set brk+=，。
set modeline
set nu
"set guifont=DejaVu\ Sans\ Mono\ Book\ 11
""set cindent
set shiftwidth=4
set ts=4
set wrap "Wrap lines
"set linebreak
set autoread
" Height of the command bar
set cmdheight=1
"设置相对当前行的标尺。原来这样设置是方便在屏幕范围内跳转，后来发现相关的跳转不便于返回跳转，快捷键``不能用，所以默认注释。
"终端背景是黑色，就让vim的背景变深，以突出文字
" set bg=dark
"貌似这种设置没效果
"set mousef
"设置命令的bash模式补全
" set wildmode=longest,list
set wildmode=list,full
" Keep 3 lines below and above the cursor
set scrolloff=3
"搜索时，每输入一个字符，都立即进行搜索。
set incsearch
set tags+=~/.vim/tags/cpp
"set tags+=~/.vim/tags/gl
set tags+=~/.vim/tags/c
set noci "no c indent"
set noai "no auto indent
set nosi "no smart indent
"set dictionary+=~/Tmp/vim-word-list/c-c++-keywords.list
" set dictionary+=~/Tmp/vim-word-list/manpage_2_3.list
"set dictionary+=~/Tmp/vim-word-list/dict-words.list
"set dictionary+=~/Tmp/vim-word-list/kmodule-tags
set infercase
" set foldcolumn=2
set foldcolumn=0
set foldlevel=1
set relativenumber
" nocompatible 在numberwidth后，会影响 numberwidth 的作用结果。
set nocompatible
set numberwidth=2
" 设置了下面两条，即使vim保存文件并退出，下次打开的时候，也依然能够进行撤销操作。
set undofile
set undodir=~/Tmp/vim-undo

"三个符号会让此命令崩溃：' " %
"下面一句作用：在vim中执行命令时，-i使得用.bashrc初始化的alias以及function的命令同样可以识别了
" set shell=/bin/bash\ -i
set shell=/bin/bash\ -c
" set shellcmdflag=-ic
" set shell=/bin/bash\ -l
" set shell=/bin/bash\ -s
" set shell=/bin/bash\ -D
" set viminfo+=!
" set grepprg=find\ .\ -name\ .git\ -prune\ -o\ -type\ f\ \\|\ xargs\ grep
" set grepprg=git\ grep\ -n
set grepprg=grep\ -no
" set makeprg=$HOME/Bin/Run\ %
" set makeprg=mm
set termencoding=&encoding
set formatprg=clang-format\ -style='{UseTab:\ Always,\ TabWidth:\ 4,\ IndentWidth:\ 4,\ BreakBeforeBraces:\ Linux,\ AllowShortIfStatementsOnASingleLine:\ false,\ IndentCaseLabels:\ false,\ ColumnLimit:\ 0}'
" }}}

" filetype {{{
filetype on
filetype plugin on
filetype plugin indent on
" filetype plugin off
" filetype plugin indent off
filetype indent on
" }}}

syntax on
" normal edit functions {{{
func! Mksession(session)
	"exe ":set ssop=blank,buffers,sesdir,resize,folds,tabpages,winpos,winsize"
" 	set ssop=blank,buffers,sesdir,resize,folds,tabpages,winpos
	set ssop=
	exe ":perl rename('".$HOME."/Tmp/vimsessions/".a:session."', '".$HOME."/Tmp/vimsessions/".a:session.".bak')"
	exe ":mksession! $HOME/Tmp/vimsessions/".a:session
endfunc
func! SourceVimrc()
	source ~/.vimrc
	redraw!
endfunc
func! Test(arg1, arg2, ...)
  echo "a:firstline = ".a:firstline
  echo "a:lastline = ".a:lastline
  echo "a:arg1 = ".a:arg1
  echo "a:arg2 = ".a:arg2
  echo "a:0 = ".a:0
  echo "a:1 = ".a:1
  echo a:000
  echo "join => ".join(a:000, '+')
  for i in a:000
	  echo "i = ".i
  endfor
endfunc
func! MksnipsChar()
	if len(a:arg) > 0
		let optl='('.a:arg
		let optr=')'
	else
		let optl=''
		let optr=''
	endif
	let name=substitute(getline("."), "\w* \*", "", "")
	let name=substitute(name, "(.*$", "", "")
	let n1=line(".")
	exe ':s/(/(${1:\/*/'
	exe ':s/, /*\/},\r${@:\/*/g'
	let n2=line(".")
	exe ':'.n1.','.n2.'Ord 1'
	exe ':'.n1.','.n2.'j'
	exe ':'.n1
	exe ':s/)/*\/})/'
	exe ':s/^\w* /if ('.optl.'/'
	exe ':s/[;]*$/'.optr.' == NULL) {/'
	exe ':normal o	perror("'.name.' failed");'
	exe ':normal oexit(EXIT_FAILURE);'
	exe ':normal o}${0}'
	exe ':normal oendsnippet'
endfunc
func! Ord(...) range
	let n1=a:firstline
	let n2=a:lastline
	if a:0 == 1
		execute ':let i='.a:1
		"execute ':' n1 ',' n2 'g/@/|let i+=1|s/@/\=i/g'
		execute ':'n1','n2'g/?@/|let i+=1|s/?@[0-9]*/\="\?@".i/g'
		execute ':let i=0'
	elseif (a:0 == 2 && a:2 !=0)
		execute ':let i='.a:1
		"execute ':'n1','n2'g/?@/|let i+=1|s/?@[0-9]*/\="\?".nr2char(64).i/g'
		execute ':'n1','n2'g/?@/|let i+='.a:2.'|s/?@[0-9]*/\="\?@".i/g'
		execute ':let i=0'
	elseif (a:0 == 2 && a:2 ==0)
		let b:ordflag=1
		execute ':' n1 ',' n2 'g/^[\t\s]*\/\/.*?@/|let b:ordflag=0'
		if b:ordflag == 1
			execute ':' n1 ',' n2 'g/?@/s!^!//!'
			let b:ordflag=0
		else
			execute ':' n1 ',' n2 'g/?@/s!^[\t\s]*//!!|normal ='
			let b:ordflag=1
		endif
	endif
endfu
func! Mform()
	execute ':% g/#include/s/ //g'
	execute ':% s/#include</#include </g'
	execute ':% s/¯/_/g'
	execute ':% s/ \. /./g'
	execute ':% s/\([a-zA-Z]\) (/\1(/g'
	execute ':% s/ , /, /g'
	execute ':% s/ ;/;/g'
	execute ':% s/−/-/g'
endfunction

func! Average(...)
	let sum = 0.0
	for nextval in a:000"a:000 is the list of arguments
		let sum += nextval
	endfor
	return sum / a:0"a:0 is the number of arguments
endfunction


func! Strcmp(str1, str2)
  if a:str1 < a:str2
	return -1
  elseif a:str1 > a:str2
	return 1
  else
	return 0
  endif
endfunction

func! Mytest(...)
	let i=0
	while i < argc()
		echo argv(i)
		let i = i + 1
	endwhile
endfunction

func! InsertCmd( cmd )
   let l = system( a:cmd . " \| sed 's/
$//g'" )
   "let l = substitute(l, '\n$', '', '')
   exe "normal a".l
   "redraw!
endfunction

func! Calc()
   let res = system("echo '".getline('.')."' | octave -q | cut -c8-")
   "let res = eval(":!octave -q | cut -c8-")
   let res = substitute(res, '\n$', '', '')
   "exe ":call setline(line('.'), res)"
   exe "normal A = ".res
   redraw!
   "exe ':! echo -n '.getline(".").'| octave -q | cut -c8-'
endfunction

func! Numopt(opt) range
	let n1=a:firstline
	let n2=a:lastline
	"exe ":".n1.",".n2."s/\\([0-9]\\+\\)/\\=eval(submatch(1)".a:opt.")/g"
	"exe ":".n1.",".n2."s/\\([0-9]\\+\\)/\\=eval(substitute(a:opt, '@', submatch(1), 'g'))/g"
	exe ":".n1.",".n2."s/\\([0-9]\\+\\)/\\=system(\"octave -q --eval 'a=\".substitute(a:opt, '@', submatch(1), 'g').\";disp(a);' | tr -d ' \\n'\")/g"
	"exe ":%g/\\([0-9]\\+\\)/"
	"set hls
endfunc

func! Numopt_vimscript0(opt) range
	let n1=a:firstline
	let n2=a:lastline
	exe ":".n1.",".n2."s/\\([0-9]\\+\\)/\\=eval(submatch(1)".a:opt.")/g"
	"exe ":".n1.",".n2."s/\\([0-9]\\+\\)/\\=eval(substitute(a:opt, '@', submatch(1), 'g'))/g"
endfunc

func! AddCodeComment() range
	let n1=a:firstline
	let n2=a:lastline
	if &filetype == "c" || &filetype == "cpp" || &filetype == "java"
		exe ":".n2." normal o/* End Added */"
		exe ":".n1." normal O/* Added by zhimincx */"
	else
		exe ":".n2." normal oEnd Added"
		call NERDComment('n', 'Comment')
		exe ":".n1." normal OAdded by zhimincx "
		call NERDComment('n', 'Comment')
	endif
endfunc
com! -range Ad <line1>,<line2>call AddCodeComment()

func! RepCodeComment() range
	let n1=a:firstline
	let n2=a:lastline
	if &filetype == "c" || &filetype == "cpp" || &filetype == "java"
		exe ":".n2." normal o/* End Replaced */"
		exe ":".n1.",".n2."co ".n2
		exe ":".n2." normal o/* To: */"
		"exe ":".n1.",".n2."+1normal \\co"
		exe ":".n1." normal O/* Replaced by zhimincx, From: */"
		" exe ":".n1."+1,".n2."+1g/^/ normal ".g:leader."cc"
		exe ":".n1."+1,".n2."+1call NERDComment('n', 'Comment')"
	else
		exe ":".n2." normal oEnd Replaced"
		call NERDComment('n', 'Comment')
		exe ":".n1.",".n2."co ".n2
		exe ":".n2." normal oTo:"
		"exe ":".n1.",".n2."+1normal \\co"
		exe ":".n1." normal OReplaced by zhimincx, From:"
		exe ":".n1.",".n2."+2call NERDComment('n', 'Comment')"
	endif
endfunc
func! Debug(pfun)
	" if a:0 == 0
	"     if strlen(@t) == 0
	"         let @t=a:pfun.a:string
	"     endif
	"     put t
	"     normal ==
	" elseif a:0 == 2
	"     if strlen(@t) == 0
	"         let @t=a:1."\n".a:pfun.a:string."\n".a:2
	"     endif
	"     put t
	"     normal -==
	" endif
	" let zhimincx_current_func=tagbar#currenttag('%s', '')
	let zhimincx_current_func=substitute(tagbar#currenttag('%s', ''), '^\(\w*\)()$', '\1', '')
	exe "normal o".a:pfun."(".zhimincx_current_func."?@0);"
endfunc
com! -range D <line1>,<line2>call Debug("ZHIMINCX_DEBUG")

" func! MyComment() range
" 	if !exists("b:comment_leader")
" 		echo "Can not comment!"
" 		return
" 	endif
" 	let flag=0
" 	for i in range(a:firstline,a:lastline)
" 		if !(match(getline(i), b:comment_leader) == 0)
" 			let flag+=1
" 			break
" 		endif
" 	endfor
" 	if (flag <= a:lastline-a:firstline+1 && flag != 0)
" 		exe ":".a:firstline.",".a:lastline."s!^!".b:comment_leader."!"
" 	else
" 		exe ":".a:firstline.",".a:lastline."s!^".b:comment_leader."!!"
" 	endif
" endfunc
func! ComDebug(opt) range
	exe ":".a:firstline
	let num1=search("Debug, zhimincx")
	let num2=search("End Debug")
	let flag=num1
	let num3=num1+1
	let num4=num2-1
	exe ":".num3.",".num4."normal ".a:opt
	let num1=search("Debug, zhimincx")
	while num1>flag && num1<a:lastline
		let num2=search("End Debug")
		let num3=num1+1
		let num4=num2-1
		exe ":".num3.",".num4."normal ".a:opt
		let num1=search("Debug, zhimincx")
	endw
endfunc
com! -range -nargs=* Cd <line1>,<line2> call ComDebug("\\c ")
func! DelDebug() range
	exe ":".a:firstline
	let sum=a:lastline
	let num1=search("Debug, zhimincx", "w")
	while num1>0 && num1<sum
		let num2=search("End Debug", "W")
		exe ":".num1.",".num2."d"
		let sum=sum-num2+num1-1
		let num1=search("Debug, zhimincx", "W")
	endw
	"exe ":".a:firstline.",".a:lastline."g/^@Chen/d"
	redraw!
endfunc
com! -range Dd <line1>,<line2> call DelDebug()

func! ComCodeComment() range
	let n1=a:firstline
	let n2=a:lastline
	if &filetype == "c" || &filetype == "cpp" || &filetype == "java"
		exe ":".n2." normal o/* End Commented */"
		exe ":".n1." normal O/* Commented by zhimincx */"
		exe ":".n1."+1,".n2."+1call NERDComment('n', 'Comment')"
	else
		exe ":".n1.",".n2."call NERDComment('n', 'Comment')"
		exe ":".n2." normal oEnd Commented"
		exe ":".n1." normal OCommented by zhimincx"
	endif
endfunc

func! Bc(...) range
	if a:0 == 1
		let pat=a:1
	else
		let pat="[0-9+\\-*\\/\\(\\)\\^]\\{1,\\}"
	endif
	exe ":".a:firstline.",".a:lastline."s/".pat."/\\=submatch(0).\" = \".substitute(system(\"echo \".escape(submatch(0), ')(').\" \| bc -l \"), \"\\\\n$\", \"\", \"\")/g"
endfunc
func! MyDeleteArround(char)
	exe "normal F".a:char
	exe "normal df".a:char
endfunc
func! MyDeleteInner(char)
	exe "normal T".a:char
	exe "normal dt".a:char
endfunc
"func! MksnipsInt(arg)
	"if len(a:arg) > 0
		"let optl='('.a:arg
		"let optr=')'
	"else
		"let optl=''
		"let optr=''
	"endif
	"let name=substitute(getline("."), "^[a-zA-Z_0-9]* ", "", "")
	"let name=substitute(name, "(.*$", "", "")
	"let n1=line(".")
	"exe ':s/(/(${1:\/*/'
	"exe ':s/, /*\/},\r${@:\/*/g'
	"let n2=line(".")
	"exe ':'.n1.','.n2.'Ord 1'
	"exe ':'.n1.','.n2.'j'
	"exe ':'.n1
	"exe ':s/)/*\/})/'
	"exe ':s/^\w* /if ('.optl.'/'
	"exe ':s/[;]*$/'.optr.' < 0) {/'
	"exe ':normal o	perror("'.name.' failed");'
	"exe ':normal oexit(EXIT_FAILURE);'
	"exe ':normal o}${0}'
	"exe ':normal oendsnippet'
"endfunc
"function! SessSave()
  "if v:this_session==""
	"call confirm("There is no loaded session","&Ok",1)
	"return
  "endif
  "if 2==confirm('Save session '.v:this_session.'?',"&No\n&Yes",1)
	"exe 'mksession! '.v:this_session
	"call confirm('Session '.v:this_session.' saved.','&Ok',1)
  "endif
"endfunction
func! Arrow(num)
	let @"='-'
	exe "normal ".a:num."p"
	normal a>
endfunction
com! -nargs=* Arrow call Arrow(<f-args>)
" }}}

" normal edit shortcuts {{{
noremap <silent>QQ :qal<CR>
noremap <silent><M-Up> @=":m -2\n"<CR>==
noremap <silent><M-Down> @=":m +1\n"<CR>==
vnoremap <silent><M-Up> @=":m '<-2\ngv"<CR>=gv
vnoremap <silent><M-Down> @=":m '>+1\ngv"<CR>=gv
inoremap <A-j> <Esc>:m .+1<CR>==gi
inoremap <A-k> <Esc>:m .-2<CR>==gi
noremap <silent><M-Left> @="xhP"<CR>
noremap <silent><M-Right> @="xp"<CR>
nnoremap <silent><expr> gp '`[' . strpart(getregtype(), 0, 1) . '`]'
vnoremap <silent><M-Left> @="xhP ".'`[' . strpart(getregtype(), 0, 1) . '`]'<CR>
vnoremap <silent><M-Right> @="xp ".'`[' . strpart(getregtype(), 0, 1) . '`]'<CR>

"nnoremap <silent> <C-S> :if expand("%") == ""<CR>browse confirm w<CR>else<CR>confirm w<CR>endif<CR>

" ctrl-s save {{{ "
com! -nargs=0 -bar Update if &modified|if empty(bufname('%'))|browse confirm write|else|confirm write|endif|endif
noremap <C-s> :update<CR>
vnoremap <C-s> <C-C>:update<CR>
inoremap <C-s> <C-O>:update<CR>
" }}} ctrl-s update "

vnoremap < <gv
vnoremap > >gv
" }}}

" common window or tab shortcuts {{{
"nnoremap <C-Up> <C-W><Up>
"nnoremap <C-Down> <C-W><Down>
"nnoremap <C-Left> <C-W><Left>
"nnoremap <C-Right> <C-W><Right>

"nnoremap <C-S-k> <C-W><Up>
"nnoremap <C-S-j> <C-W><Down>
"nnoremap <C-S-h> <C-W><Left>
"nnoremap <C-S-l> <C-W><Right>
"nnoremap <C-S-w> <C-W>+
"nnoremap <C-S-s> <C-W>-
"nnoremap <C-S-a> <C-W><
"nnoremap <C-S-d> <C-W>>
"nnoremap <C-S-w> @=nr2char(23)."+"<cr>
"nnoremap <C-S-s> @=nr2char(23)."-"<cr>
"nnoremap <C-S-a> @=nr2char(23).">"<cr>
"nnoremap <C-S-d> @=nr2char(23)."<"<cr>
"nnoremap <C-S-q> @=nr2char(23)."c"<cr>
"在不脱离终端的情况下，那些特殊键实在不好绑定。
"set <C-S-k>=^[[1;2A <C-S-j>=^[[1;2B <C-S-l>=^[[1;2C <C-S-h>=^[[1;2D
"set <C-S-w>=^[[1;3A <C-S-s>=^[[1;3B <C-S-a>=^[[1;3C <C-S-d>=^[[1;3D
"nnoremap <C-S-k> :wincmd k<CR>
"nnoremap <C-S-j> :wincmd j<CR>
"nnoremap <C-S-h> :wincmd h<CR>
"nnoremap <C-S-l> :wincmd l<CR>
"nnoremap <C-S-w> :wincmd +<CR>
"nnoremap <C-S-s> :wincmd -<CR>
"nnoremap <C-S-a> :wincmd <<CR>
"nnoremap <C-S-d> :wincmd ><CR>

nnoremap <Space>k @=":wincmd k\n"<CR>
nnoremap <Space>j @=":wincmd j\n"<CR>
nnoremap <Space>h @=":wincmd h\n"<CR>
nnoremap <Space>l @=":wincmd l\n"<CR>
" nnoremap <Space>w @=":wincmd k\n"<CR>
" nnoremap <Space>s @=":wincmd j\n"<CR>
" nnoremap <Space>a @=":wincmd h\n"<CR>
" nnoremap <Space>d @=":wincmd l\n"<CR>
" nnoremap <Space>s :split<cr>
" nnoremap <Space>v :vsplit<cr>
" nnoremap <Space>t :tabedit<cr>
nnoremap <Space>_ @=":wincmd _\n"<CR>
nnoremap <Space>= @=":wincmd =\n"<CR>
nnoremap <Space>t @=":wincmd t\n"<CR>
nnoremap <Space>b @=":wincmd b\n"<CR>
nnoremap <C-Up> @=":resize +3\n"<CR>
nnoremap <C-Down> @=":resize -3\n"<CR>
nnoremap <C-Left> @=":vert resize -5\n"<CR>
nnoremap <C-Right> @=":vert resize +5\n"<CR>

nnoremap gt @="gt"<CR>
nnoremap gT @="gT"<CR>
" }}}

" special path config {{{
" let s:local_path="/home/thomas/Downloads/chv-dukpt"
" if !(match($PWD, s:local_path) < 0)
" 	if !(match(expand("%:t"), "[tT]est") < 0)
" 		highlight MyKeyWord cterm=bold ctermbg=green gui=bold guibg=green
" 		call matchadd('MyKeyWord', '\(\<DukptEncryptPin\>\|\<verifyDukpt\>\|\<setDukptType\>\)', 201)
" 	endif
" endif

" " 下面一段不可以放在bundle目录中，切记！
" let s:local_path="/home/thomas/Note"
" if !(match($PWD, s:local_path) < 0)
" 	"let g:pathogen_disabled=[]
" 	"call add(g:pathogen_disabled, 'clang_complete')
" 	if !(match(expand("%:t"), "dukpt-test") < 0)
" 		highlight MyKeyWord ctermfg=white ctermbg=darkblue guifg=white guibg=darkblue
" 		call matchadd('MyKeyWord', '\(\<DukptEncryptPin\>\|\<verifyDukpt\>\|\<setDukptType\>\)', 201)
" 	endif
" 	let sfxlist=["c", "cpp", "h", "mk", "java", "sh", "xml", "html"]
" 	let ftlist=["c", "cpp", "cpp", "make", "java", "sh", "xml", "html"]
" 	let i=-1
" 	for sfx in sfxlist
" 		let i+=1
" 		if split(expand("%:t"), "_")[-1] == sfx
" 			exe "set filetype=".ftlist[i]
" 			highlight NoteFiles cterm=bold ctermbg=green gui=bold guibg=green
" 			call matchadd('NoteFiles', '^.*\(\.c:\|：\|\.h:\|\.cpp:\|\.java:\|\.xml:\)$', 201)
" 			highlight NoteItems cterm=bold ctermbg=gray gui=bold guibg=gray
" 			call matchadd('NoteItems', '^.*=>', 202)
" 			break
" 		endif
" 	endfor
" endif

" com! -range D <line1>,<line2>call Debug("printf","(\"T#%s:%d?@0\\n\", FILENAME, __LINE__);")
com! -range D <line1>,<line2>call Debug("printf","(\"Chen: %s:%d %s?@0\\n\", __FILE__, __LINE__, __func__);")
let s:pathpattern='/u-\?boot[^/]*'
if expand("%:p") =~ s:pathpattern
	let g:local_root = substitute(expand("%:p"), '\(.*'.s:pathpattern.'\).*', '\1', "")
	let &makeprg="cd ".g:local_root."; ./build_uboot.sh"
	nnoremap <leader>ff :exe 'call system("sudo -A fastboot flash bootloader $(ls --sort=time '.g:local_root.'/u-boot-* \| head -2 \| grep -- -sc.bin)")'<CR>
	nnoremap <leader>rb :!sudo -A fastboot reboot<CR>
endif
let s:pathpattern="/xboot-ing-jb"
if expand("%:p") =~ s:pathpattern
	let g:local_root = substitute(expand("%:p"), '\(.*'.s:pathpattern.'\).*', '\1', "")
" 	com! -range D <line1>,<line2>call Debug("debug","(\"##Thomas: %d %s?@0 ~~\\t\", __LINE__, __func__);")
	let &makeprg="cd ".g:local_root."; ./build_xboot_especial_team.sh"
	nnoremap <leader>ff :exe 'call system("sudo -A fastboot flash bootloader $(ls --sort=time '.g:local_root.'/mbr-xboot-* \| head -2 \| grep -- -s.bin)")'<CR>
	nnoremap <leader>rb :!sudo -A fastboot reboot<CR>
endif
" Replaced by ThomasChen, From:
" let s:pathpattern="/lk"
" if expand("%:p") =~ s:pathpattern
	" " echo s:pathpattern
	" let g:local_root = substitute(expand("%:p"), '\(.*'.s:pathpattern.'\).*', '\1', "")
	" " echo g:local_root
	" let &makeprg="cd ".g:local_root."/../../..; ./mk r lk"
	" " echo "123456"
	" " echo &makeprg
" endif
" To:
let s:pathpattern="/lk"
if expand("%:p") =~ s:pathpattern
	set noautochdir
	cd /data/androidh0/bootable/bootloader/lk
	" let &makeprg="cd /data/androidh0; ./mk -t r lk"
	let &makeprg="cd /data/androidh0; ./build_boot.sh"
	nnoremap <F6> :Gdiff master<cr>
endif
" End Replaced
" let s:local_path="/kernel404"
" if !(match(getcwd(), s:local_path) < 0)
	" com! -range D <line1>,<line2>call Debug("printk","(KERN_ERR \"Chen: %s:%d %s?@0\\n\", __FILE__, __LINE__, __func__);")
" endif

let s:local_path="/kernelflinger"
if !(match(getcwd(), s:local_path) < 0)
	let &makeprg="cd /home/czm/Codes/bxtp_ivi_m; make -j4 kernelflinger-userdebug"
endif

" let s:pathpattern='/android*'
" if expand("%:p") =~ s:pathpattern
	" set makeprg=mm
" endif
" }}}

" for plugins {{{
" vim-easy-align {{{
" Start interactive EasyAlign in visual mode (e.g. vipga)
xmap ga <Plug>(EasyAlign)
" Start interactive EasyAlign for a motion/text object (e.g. gaip)
nmap ga <Plug>(EasyAlign)
" }}}
" OmniCppComplete {{{
let OmniCpp_NamespaceSearch = 1
let OmniCpp_GlobalScopeSearch = 1
let OmniCpp_ShowAccess = 1
let OmniCpp_ShowPrototypeInAbbr = 1 " show function parameters
let OmniCpp_MayCompleteDot = 1 " autocomplete after .
let OmniCpp_MayCompleteArrow = 1 " autocomplete after ->
let OmniCpp_MayCompleteScope = 1 " autocomplete after ::
let OmniCpp_DefaultNamespaces = ["std", "_GLIBCXX_STD"]
" automatically open and close the popup menu / preview window
au CursorMovedI,InsertLeave * if pumvisible() == 0|silent! pclose|endif
set completeopt=menuone,menu,longest,preview


" Octave syntax
augroup filetypedetect
  au! BufRead,BufNewFile *.m,*.oct set filetype=octave
augroup END
" Use keywords from Octave syntax language file for autocomplete
if has("autocmd") && exists("+omnifunc")
   autocmd Filetype octave if &omnifunc == ""|setlocal omnifunc=syntaxcomplete#Complete|endif
endif

if has("autocmd")
	autocmd FileType css setlocal omnifunc=csscomplete#CompleteCSS
	autocmd FileType html,markdown setlocal omnifunc=htmlcomplete#CompleteTags
	autocmd FileType javascript setlocal omnifunc=javascriptcomplete#CompleteJS
	autocmd FileType python setlocal omnifunc=pythoncomplete#Complete
	autocmd FileType xml setlocal omnifunc=xmlcomplete#CompleteTags
	autocmd FileType php setlocal omnifunc=xmlcomplete#CompletePHP
	autocmd Filetype java setlocal omnifunc=javacomplete#Complete 
	autocmd FileType matlab setlocal keywordprg=info\ octave\ --vi-keys\ --index-search
	autocmd FileType octave setlocal keywordprg=xterm\ -e\ info\ octave\ --vi-keys\ --index-search
	autocmd FileType octave setlocal keywordprg=xterm\ -fa\ 'DejaVu\ Sans\ Mono:style=Book'\ -fs\ 12\ -geometry\ 80x50\ -e\ info\ octave\ --vi-keys\ --index-search
	autocmd FileType c,cpp,java,scala		let b:comment_leader = '// '
	autocmd FileType sh,ruby,python			let b:comment_leader = '# '
	autocmd FileType conf,fstab				let b:comment_leader = '# '
	autocmd FileType tex,matlab,octave	    let b:comment_leader = '% '
	autocmd FileType mail					let b:comment_leader = '> '
	autocmd FileType vim					let b:comment_leader = '" '
" 	autocmd Filetype vim					let &foldtext='{{{','}}}'
	autocmd Filetype vim					setlocal foldmethod=marker
endif 
" }}}
" vim-multiple-cursors {{{
" Default highlighting (see help :highlight and help :highlight-link)
" highlight multiple_cursors_cursor term=reverse cterm=reverse gui=reverse
" highlight link multiple_cursors_visual Visual
" let g:multi_cursor_exit_from_visual_mode=0
let g:multi_cursor_exit_from_insert_mode=0
" let g:multi_cursor_normal_maps = {'f':1, 'F':1, 't':1, 'T':1, 'y':1, '/':1, '?':1, 'r':1, 'R':1, 'g':1, '"':1, 'z':1}
" let g:multi_cursor_exit_from_insert_mode=0
" }}}
" CoVim {{{
let CoVim_default_name = "thomas"
let CoVim_default_port = "6349"
" }}}
" ConqueGdb {{{
" let g:ConqueGdb_SrcSplit = 'above'
" let g:ConqueGdb_GdbExe = 'arm-linux-gnueabihf-gdb'
" let g:ConqueGdb_SaveHistory = 0
let g:ConqueGdb_Leader = '0'
let g:ConqueGdb_Run = g:ConqueGdb_Leader . 'r'
let g:ConqueGdb_Continue = g:ConqueGdb_Leader . 'c'
let g:ConqueGdb_Next = g:ConqueGdb_Leader . 'n'
let g:ConqueGdb_Step = g:ConqueGdb_Leader . 's'
let g:ConqueGdb_Print = g:ConqueGdb_Leader . 'p'
let g:ConqueGdb_ToggleBreak = g:ConqueGdb_Leader . 'b'
let g:ConqueGdb_SetBreak = g:ConqueGdb_Leader . 'b'
let g:ConqueGdb_DeleteBreak = g:ConqueGdb_Leader . 'd'
let g:ConqueGdb_Finish = g:ConqueGdb_Leader . 'f'
let g:ConqueGdb_Backtrace = g:ConqueGdb_Leader . 't'
nnoremap <silent> <Leader>Y :ConqueGdbCommand y<CR>
nnoremap <silent> <Leader>N :ConqueGdbCommand n<CR>
nnoremap <Leader>cg :ConqueGdb 
" }}}
" vim-gitgutter {{{
let g:gitgutter_max_signs=3600
" }}}
" airline {{{
"powerline{
" set guifont=PowerlineSymbols\ for\ Powerline
set t_Co=256
" set t_AB=<Esc>[48;5;%dm
" set t_AF=<Esc>[38;5;%dm
let g:Powerline_symbols = 'fancy'
"}

let g:airline_powerline_fonts=1
"  Replaced by ThomasChen, From:
" let g:airline_themes='jellybeans'
"  To:
"  Replaced by ThomasChen, From:
" let g:airline_themes='powerlineish'
"  To:
" let g:airline_themes='kolor'
"  End Replaced
"  End Replaced
if !exists('g:airline_symbols')
  let g:airline_symbols = {}
endif
let g:airline_symbols.space = "\ua0"
" solarized options 
set term=xterm-256color
let g:solarized_visibility = "high"
let g:solarized_contrast = "high"
" set t_Co=16
" let g:solarized_termcolors=16
let g:airline#extensions#tabline#enabled = 1
" let g:airline_theme='molokai'
" let g:airline_theme='cool'
" let g:airline_theme='powerlineish'
" let g:airline_theme='term'
let g:airline_theme='raven'
" colorscheme elflord

" func! AirlineInit()
" 	let g:airline_section_a = airline#section#create(['mode', ' ', 'branch'])
" 	let g:airline_section_b = airline#section#create_left(['ffenc', 'hunks', '%f'])
" 	let g:airline_section_c = airline#section#create(['filetype'])
" 	let g:airline_section_x = airline#section#create(['%P'])
" 	let g:airline_section_y = airline#section#create(['%B'])
" 	let g:airline_section_z = airline#section#create_right(['%l', '%c'])
" endfunc

" autocmd VimEnter * call AirlineInit()
let g:airline_detect_whitespace=0
let g:airline_section_y = airline#section#create(['%B'])
" }}}
" taglist_46 {{{
""let Tlist_Auto_Open = 1
let Tlist_Ctags_Cmd = '/usr/bin/ctags'
let Tlist_Show_One_File = 1
let Tlist_Exit_OnlyWindow = 1
" "}}}
" clang_complete {{{
let g:clang_user_options='|| exit 0'
let g:clang_complete_auto = 1
let g:clang_complete_copen = 1
" }}}
" cscope {{{
if has("cscope")

	""""""""""""" Standard cscope/vim boilerplate

	" use both cscope and ctag for 'ctrl-]', ':ta', and 'vim -t'
	set cscopetag

	" check cscope for definition of a symbol before checking ctags: set to 1
	" if you want the reverse search order.
	set csto=0

" 	"  Replaced by ThomasChen, From:
" 	" add any cscope database in current directory
" 	if filereadable("cscope.out")
" 		cs add cscope.out  
" 	" else add the database pointed to by environment variable 
" 	elseif $CSCOPE_DB != ""
" 		cs add $CSCOPE_DB
" 	endif
" 	 To:
	" Replaced by ThomasChen, From:
	" let thomas_curpath=expand("%:p:h")
	" To:
	" Avoid adding ./cscope.out repeatedly.
	" let thomas_curpath=system("dirname $(readlink -znf .) | tr -d [:cntrl:] ")
	let thomas_curpath=system("readlink -znf . | tr -d [:cntrl:] ")
	" End Replaced
	while thomas_curpath != "/"
		if filereadable(thomas_curpath."/.cfg.vim")
			exe "source ".thomas_curpath."/.cfg.vim"
		endif
		if filereadable(thomas_curpath."/cscope.out")
			exe "silent cscope add ".thomas_curpath."/cscope.out"
			if filereadable(thomas_curpath."/tags")
				exe "silent set tags=".thomas_curpath."/tags"
			endif
			break
		endif
		let tmparg=fnamemodify(thomas_curpath, ":t")
		let thomas_curpath=fnamemodify(thomas_curpath, ":p:h:h")
	endwhile
	unlet thomas_curpath
" 	 End Replaced

	" show msg when any other cscope db added
	set cscopeverbose  
	nmap <C-\>s :cs find s <C-R>=expand("<cword>")<CR><CR>	
	nmap <C-\>g :cs find g <C-R>=expand("<cword>")<CR><CR>	
	nmap <C-\>c :cs find c <C-R>=expand("<cword>")<CR><CR>	
	nmap <C-\>t :cs find t <C-R>=expand("<cword>")<CR><CR>	
	nmap <C-\>e :cs find e <C-R>=expand("<cword>")<CR><CR>	
	nmap <C-\>f :cs find f <C-R>=expand("<cfile>")<CR><CR>	
	nmap <C-\>i :cs find i ^<C-R>=expand("<cfile>")<CR>$<CR>
	nmap <C-\>d :cs find d <C-R>=expand("<cword>")<CR><CR>	
	nmap <C-@>s :scs find s <C-R>=expand("<cword>")<CR><CR>	
	nmap <C-@>g :scs find g <C-R>=expand("<cword>")<CR><CR>	
	nmap <C-@>c :scs find c <C-R>=expand("<cword>")<CR><CR>	
	nmap <C-@>t :scs find t <C-R>=expand("<cword>")<CR><CR>	
	nmap <C-@>e :scs find e <C-R>=expand("<cword>")<CR><CR>	
	nmap <C-@>f :scs find f <C-R>=expand("<cfile>")<CR><CR>	
	nmap <C-@>i :scs find i ^<C-R>=expand("<cfile>")<CR>$<CR>	
	nmap <C-@>d :scs find d <C-R>=expand("<cword>")<CR><CR>	
	nmap <C-@><C-@>s :vert scs find s <C-R>=expand("<cword>")<CR><CR>
	nmap <C-@><C-@>g :vert scs find g <C-R>=expand("<cword>")<CR><CR>
	nmap <C-@><C-@>c :vert scs find c <C-R>=expand("<cword>")<CR><CR>
	nmap <C-@><C-@>t :vert scs find t <C-R>=expand("<cword>")<CR><CR>
	nmap <C-@><C-@>e :vert scs find e <C-R>=expand("<cword>")<CR><CR>
	nmap <C-@><C-@>f :vert scs find f <C-R>=expand("<cfile>")<CR><CR>	
	nmap <C-@><C-@>i :vert scs find i ^<C-R>=expand("<cfile>")<CR>$<CR>	
	nmap <C-@><C-@>d :vert scs find d <C-R>=expand("<cword>")<CR><CR>
endif
" }}}
" WMToggle {{{
"let g:winManagerWindowLayout="FileExplorer|TagList"
let g:winManagerWindowLayout="NERDTree|TagBar"
"以w/W开头的快捷键会影响到光标在单词间移动的功能;
nmap <leader>wm : WMToggle<cr>
" }}}
" fzf {{{
set rtp+=~/.fzf
" }}}
" ag {{{
"  Replaced by ThomasChen, From:
" nnoremap <silent><leader>ag :exe ":Ag ".expand('<cword>')." ".input("Input dir/file: ")<cr>
" nnoremap <silent><leader>aa :exe ":AgAdd ".expand('<cword>')." ".input("Input dir/file: ")<cr>
"  To:
func! ThomasAgSearch(pattern, type)
	let b:ag_path=input('Input dir/file: ')
	if strlen(b:ag_path) != 0
		if a:type == 0
			exe "Ag ".a:pattern." ".b:ag_path
		else
			exe "AgAdd ".a:pattern." ".b:ag_path
		endif
	endif
endfunc
nnoremap <silent><leader>ag :call ThomasAgSearch(expand('<cword>'), 0)<cr>
nnoremap <silent><leader>aa :call ThomasAgSearch(expand('<cword>'), 1)<cr>
" vnoremap <silent><leader>ag :call ThomasAgSearch(expand('<cword>'), 0)<cr>
" vnoremap <silent><leader>aa :call ThomasAgSearch(expand('<cword>'), 1)<cr>
"  End Replaced
" }}}
" gundo {{{
nnoremap <leader>ud :GundoToggle<CR>
" }}}
" ultisnips {{{
" Track the engine.
"Plugin 'SirVer/ultisnips'
" Snippets are separated from the engine. Add this if you want them:
"Plugin 'honza/vim-snippets'
" Trigger configuration. Do not use <tab> if you use https://github.com/Valloric/YouCompleteMe.
"let g:UltiSnipsExpandTrigger="<c-tab>"
""let g:UltiSnipsJumpForwardTrigger="<c-b>"
"let g:UltiSnipsJumpForwardTrigger="<tab>"
"let g:UltiSnipsJumpBackwardTrigger="<c-z>"
" If you want :UltiSnipsEdit to split your window.
let g:UltiSnipsEditSplit="vertical"
" }}}
" tagbar {{{
"let g:tagbar_autopreview = 1
nnoremap <leader>tb :TagbarToggle<CR>
" }}}
" ctrlp {{{
let g:ctrlp_map = '<c-p>'
let g:ctrlp_cmd = 'CtrlP'
let g:ctrlp_user_command = 'cat %s/cscope.files'
" let g:ctrlp_user_command = 'find %s -maxdepth 2 -type f'
"let g:loaded_ctrlp = 1
"let g:ctrlp_by_filename = 0
let g:ctrlp_tabpage_position = 'ac'
let g:ctrlp_working_path_mode = 'a'
let g:ctrlp_follow_symlinks = 1
" }}}
" utl.vim {{{
nnoremap <silent>go :Utl ol<cr>
":nmap <2-LeftMouse> :Utl ol<cr>
" }}}
" vim-easymotion {{{
map , <Plug>(easymotion-prefix)
map ,l <Plug>(easymotion-lineforward)
map ,j <Plug>(easymotion-j)
map ,k <Plug>(easymotion-k)
map ,h <Plug>(easymotion-linebackward)
" }}}
" YankRing.vim {{{
nnoremap <silent> <F10> :YRShow<CR>
" }}}
" FuzzyFinder {{{
	nnoremap <leader>fb :FufBuffer<cr>
	nnoremap <leader>fl :FufLine<cr>
" }}}
" nerdcommenter {{{
" let g:NERD_c_alt_style=5
" let g:NERDSpaceDelims=1
" let g:NERDCustomDelimiters = { 'c' : { 'left': '//', 'leftAlt': '/*', 'rightAlt': '*/' }, 'py' : { 'left': '# ', 'leftAlt': '', 'rightAlt': '' }}
" " 在文件中，‘添加注释’操作与原注释无关。
" " let g:NERDUsePlaceHolders=0
" let g:NERDLPlace='/*'
" let g:NERDRPlace='*/'
" let g:NERDCompactSexyComs=0
" " 在文件中，‘取消注释’操作与/**/无关。
" " let g:NERDRemoveAltComs=0

" Add spaces after comment delimiters by default
let g:NERDSpaceDelims = 1

" Use compact syntax for prettified multi-line comments
let g:NERDCompactSexyComs = 1

" Align line-wise comment delimiters flush left instead of following code indentation
let g:NERDDefaultAlign = 'left'

" Set a language to use its alternate delimiters by default
let g:NERDAltDelims_java = 1

" Add your own custom formats or override the defaults
" let g:NERDCustomDelimiters = { 'c': { 'left': '/**','right': '*/' } }
" let g:NERDCustomDelimiters = { 'c': { 'left': '//','right': '' } }
let g:NERDCustomDelimiters = { 'c' : { 'left': '//', 'leftAlt': '/*', 'rightAlt': '*/' }, 'py' : { 'left': '# ', 'leftAlt': '', 'rightAlt': '' }}

" Allow commenting and inverting empty lines (useful when commenting a region)
let g:NERDCommentEmptyLines = 1

" Enable trimming of trailing whitespace when uncommenting
let g:NERDTrimTrailingWhitespace = 1
" }}}
" netrw {{{
let g:netrw_uid='anonymous'
" let g:netrw_passwd=''
" }}}
" NERDTree {{{
let NERDTreeIgnore=['\~$', '.o$', '__pycache__']
" }}}
" vim-dirdiff {{{
      let g:DirDiffExcludes = "CVS,*.class,*.exe,.*.swp"
      let g:DirDiffIgnore = "Id:,Revision:,Date:"
      let g:DirDiffSort = 1
      let g:DirDiffWindowSize = 14
      let g:DirDiffIgnoreCase = 0
      let g:DirDiffDynamicDiffText = 0
	  if $LC_ALL == "zh_CN.utf8" || ($LC_ALL == "" && $LANG == "zh_CN.utf8")
		  let g:DirDiffTextFiles = "文件 "
		  let g:DirDiffTextAnd = " 和 "
		  let g:DirDiffTextDiffer = " 不同"
		  let g:DirDiffTextOnlyIn = "只在 "
		  let g:DirDiffTextOnlyInCenter = " 存在："
	  else
		  let g:DirDiffTextFiles = "Files "
		  let g:DirDiffTextAnd = " and "
		  let g:DirDiffTextDiffer = " differ"
		  let g:DirDiffTextOnlyIn = "Only in "
		  let g:DirDiffTextOnlyInCenter = ": "
	  endif
" }}}
" mru {{{
      " let MRU_Use_Current_Window = 1
      " let MRU_File = 'd:\myhome\_vim_mru_files'
      " let MRU_Max_Entries = 1000
      " let MRU_Exclude_Files = '^/tmp/.*\|^/var/tmp/.*'  " For Unix
      " let MRU_Exclude_Files = '^c:\\temp\\.*'           " For MS-Windows
      " let MRU_Include_Files = '\.c$\|\.h$'
      " let MRU_Window_Height = 15
      " let MRU_Use_Current_Window = 1
      " let MRU_Auto_Close = 0
      " let MRU_Add_Menu = 0
      " let MRU_Max_Menu_Entries = 20
      " let MRU_Max_Submenu_Entries = 15
      " let MRU_Filename_Format={'formatter':'v:val', 'parser':'.*'}
" }}}
" agrep {{{
let g:agrep_default_flags='-Ir --exclude-dir=.{git,svn} --exclude=tags --exclude=cscope.*'
map <Leader>] :<C-U>exe v:count1.(bufwinnr('Agrep') == -1 ? 'cn' : 'Anext')<CR>
map <Leader>[ :<C-U>exe v:count1.(bufwinnr('Agrep') == -1 ? 'cp' : 'Aprev')<CR>
" }}}
" rainbow_parentheses {{{
let g:rbpt_colorpairs = [
    \ ['brown',       'RoyalBlue3'],
    \ ['Darkblue',    'SeaGreen3'],
    \ ['darkgray',    'DarkOrchid3'],
    \ ['darkgreen',   'firebrick3'],
    \ ['darkcyan',    'RoyalBlue3'],
    \ ['darkred',     'SeaGreen3'],
    \ ['darkmagenta', 'DarkOrchid3'],
    \ ['brown',       'firebrick3'],
    \ ['gray',        'RoyalBlue3'],
    \ ['black',       'SeaGreen3'],
    \ ['darkmagenta', 'DarkOrchid3'],
    \ ['Darkblue',    'firebrick3'],
    \ ['darkgreen',   'RoyalBlue3'],
    \ ['darkcyan',    'SeaGreen3'],
    \ ['darkred',     'DarkOrchid3'],
    \ ['red',         'firebrick3'],
    \ ]
let g:rbpt_max = 16
let g:rbpt_loadcmd_toggle = 0
" :RainbowParenthesesToggle       " Toggle it on/off
" :RainbowParenthesesLoadRound    " (), the default when toggling
" :RainbowParenthesesLoadSquare   " []
" :RainbowParenthesesLoadBraces   " {}
" :RainbowParenthesesLoadChevrons " <>
au VimEnter * RainbowParenthesesToggle
au VimEnter * RainbowParenthesesLoadRound
au VimEnter * RainbowParenthesesLoadSquare
au VimEnter * RainbowParenthesesLoadBraces
" End Replaced
" }}}
" sideways.vim {{{
nnoremap <c-h> :SidewaysLeft<cr>
nnoremap <c-l> :SidewaysRight<cr>
" }}}
" vim-markdown {{{
"let g:vim_markdown_folding_disabled = 1
"let g:vim_markdown_folding_style_pythonic = 1
"let g:vim_markdown_folding_level = 6
"let g:vim_markdown_no_default_key_mappings = 1
"let g:vim_markdown_toc_autofit = 1
"let g:vim_markdown_emphasis_multiline = 0
"set conceallevel=2
"let g:vim_markdown_conceal = 0
"let g:vim_markdown_fenced_languages = ['csharp=cs']
"let g:vim_markdown_math = 1
"let g:vim_markdown_frontmatter = 1
"let g:vim_markdown_toml_frontmatter = 1
"let g:vim_markdown_json_frontmatter = 1
"let g:vim_markdown_new_list_item_indent = 2
" }}}
" }}}

" normal command {{{
com! -range -nargs=* Ms call Mksession(<f-args>)
com! Sv call SourceVimrc()
com! Calc .!xargs -I {} octave -q --eval "try;a=eval('{}');fprintf('{} = ');disp(a);catch;fprintf('{}\n');end;"
" map <C-F12> :!ctags -R --sort=yes --c++-kinds=+p --fields=+iaS --extra=+q .<CR>
"以t/T开头的快捷键会影响到光标在行中的搜索功能。
"nmap td !!today-date<cr>
com! Reload e!%:p
com! -range -nargs=* Tt <line1>,<line2>call Test(<f-args>)
com! -range -nargs=* Ord <line1>,<line2>call Ord(<f-args>)
command! -nargs=* -complete=shellcmd R botright 24vnew | setlocal buftype=nofile bufhidden=hide noswapfile | 0r !<args>
com! Indent !indent -linux %
":com! Debug !gcc -Wall % -o /tmp/a.out
com! Debug !make
" :com! Run !bash -c ".bin/%:r"
com! -range Cm <line1>,<line2>call ComCodeComment()
com! -range -nargs=* Bc <line1>,<line2>call Bc(<f-args>)
com! -range -nargs=* Rp <line1>,<line2>call RepCodeComment(<f-args>)
" }}}

" for abbreviate {{{
cab t tabedit
cab ub /ram/tst/uboot404/
cab xb /ram/tst/xboot-ing-jb/

let s:pathpattern='/ram/tst'
if getcwd() =~ s:pathpattern
	ab ti token_imageInfo
	ab tk token
	ab TE TOKEN_LOG_ERROR
	ab TI TOKEN_LOG_INFO
	ab TD TOKEN_LOG_DEBUG
	ab TW TOKEN_WINTERSOLSTICE_IMAGE_INFO_INDEX
	ab TB TOKEN_BOOTLOADER_IMAGE_INFO_INDEX
	ab TK TOKEN_KERNEL_IMAGE_INFO_INDEX
	ab TS TOKEN_SYSTEM_IMAGE_INFO_INDEX
	ab TN TOKEN_INDEX_NUMBER
endif
" }}}

" some map {{{
" noremap <silent><leader>co :call MyComment()<cr>
" vnoremap <silent><leader>co :call MyComment()<cr>
nnoremap <silent>,t :exe ":w ".tempname()<CR>
nnoremap <silent><leader>mksc :call MksnipsChar(input(""))<CR>
"添加windows下面复制（crtl+c）,粘贴（ctrl+v）ctrl+A 等快捷键
"快捷键列选冲突，注释掉
"source /usr/share/vim/vim74/mswin.vim
"behave mswin
"tab的定义不仅毫无用处，而且居然stealed my Ctrl-i such that I can't jump back from the latest open file
"nnoremap <Tab> >>_
"nnoremap <S-Tab> <<_
"inoremap <S-Tab> <C-D>
noremap <silent><leader>hl :set hls!<CR>
noremap <silent><leader>ru :set rnu!<CR>
nmap <leader>td :s/^/\=strftime("%F", localtime())<cr>

"可能snippetsEmu是个比较牛的插件，我暂时把它给留着，快捷键冲突的地方也改改。
"let g:snippetsEmu_key = "`"

source $VIMRUNTIME/ftplugin/man.vim
nnoremap K :Man <C-R><C-W><CR>

vnoremap <leader>a1 :call Numopt_vimscript0("+1")<CR>


"nnoremap <space> @=":wincmd ".nr2char(getchar())."\n"<CR>

vnoremap <silent><leader>bct :B !column -t<CR>
vnoremap <silent><leader>erd :g/^$/d<CR>


"nnoremap <silent><leader>da :call MyDeleteArround(input(""))<CR>
"nnoremap <silent><leader>di :call MyDeleteInner(input(""))<CR>
"nnoremap <silent><leader>ca :call MyDeleteArround(input(""))<CR>
"nnoremap <silent><leader>ci :call MyDeleteInner(input(""))<CR>
nnoremap <silent>da/ :call MyDeleteArround("/")<CR>
nnoremap <silent>di/ :call MyDeleteInner("/")<CR>
nnoremap <silent>ca/ :call MyDeleteArround("/")<CR>i
nnoremap <silent>ci/ :call MyDeleteInner("/")<CR>i

"nnoremap <silent><leader>mksi :call MksnipsInt(input(""))<CR>

"noremap j gj
"noremap k gk
" highlight last inserted text
nnoremap <silent>gV `[v`]
vnoremap <silent>p p`[v`]y
"nnoremap <leader>ev :vsp $MYVIMRC<CR>
"nnoremap <leader>ed :vsp ~/Tmp/vim-word-list<CR>
"nnoremap <leader>euc :vsp ~/.vim/UltiSnips/c.snippets<CR>
"nnoremap <leader>eup :vsp ~/.vim/bundle/vim-snippets/UltiSnips/cpp.snippets<CR>
"nnoremap <leader>eb :vsp ~/.bashrc<CR>
"nnoremap <leader>ev :so ~/Tmp/vimsessions/usual-vim-config<CR>

"command! -bar SessSave call SessSave()
"nnoremap <leader>ss :SessSave<CR>

"nnoremap <CR> G
"nnoremap <BS> gg
map q: :q

nnoremap <leader>se :set ignorecase<cr>:set hls<cr>/\<error\><cr>
nnoremap <silent><leader>ek :!ek;exit<cr>:redraw<cr>
nnoremap <silent><leader>wr :set wrap!<cr>
nnoremap <silent><leader>bi :exe ":topleft 10new\| setlocal buftype=nofile bufhidden=hide noswapfile \| 0r !bi ".input("input exe args: ")<cr>
nnoremap <silent><leader>df :set diff<cr>:set scrollbind<cr>:set cursorbind<cr>:set scrollopt+=hor<cr>:set nowrap<cr>:set foldmethod=diff<cr>:set foldcolumn=0<cr>
nnoremap <silent><F6> :Gdiff master<cr>

"map <F9> :echo "hi<" . synIDattr(synID(line("."),col("."),1),"name") . '> trans<' . synIDattr(synID(line("."),col("."),0),"name") . "> lo<" . synIDattr(synIDtrans(synID(line("."),col("."),1)),"name") . ">"<CR>

nnoremap <F2> :exe ":lvimgrep ".input("Pattern: ")." %"<cr>
vnoremap <F2> :exe :<c-u>exe "lvimgrep ".expand("<cword>")." %"<cr>

vmap gq gqg'[V']=

map <leader>gd :Gvdiff ~1<cr>

" func! Thomas_GitCheckFile()
	" botright 48vnew
	" setlocal buftype=nofile bufhidden=hide noswapfile wfw nonu nornu syntax=git
	" exe ":0r !git log ".expand("%")
	" exe ":Glog"
	" " redraw!
" endfunc

let g:thomas_git_check_uid=0
" if expand("%") == "d-list"
	" let g:thomas_git_check_uid=100
" endif
" if expand("%") == "e-list"
	" let g:thomas_git_check_uid=101
" endif
" if expand("%") == "y-list"
	" let g:thomas_git_check_uid=101
" endif
func! Thomas_GitCheckFile()
	" if g:thomas_git_check_uid == 0
		" " Replaced by ThomasChen, From:
		" " let g:thomas_git_check_uid=input("UID?")
		" " To:
		" echo "UID?"
		" let g:thomas_git_check_uid=getchar()
		" " End Replaced
	" endif
	" Replaced by ThomasChen, From:
	" if g:thomas_git_check_uid == char2nr('d') "d
		" Gllog --author=dayong.xie --date=short
	" elseif g:thomas_git_check_uid == char2nr('e') "e
		" Gllog --author=edward.wang --date=short
	" elseif g:thomas_git_check_uid == char2nr('h') "h
		" Gllog --author=jinhaiqing --author=hans.dailybuild --date=short
	" elseif g:thomas_git_check_uid == char2nr('y') "y
		" Gllog --author=Maobiao.Yao --author=YaoMaoBiao --date=short
	" elseif g:thomas_git_check_uid == char2nr('t') "t
		" Gllog --author=thomas --author=Thomas\ Chen --date=short
	" elseif g:thomas_git_check_uid == char2nr('z') "z
		" Gllog --author=yue\ zhong --date=short
	" endif
	" To:
	" if g:thomas_git_check_uid == 'd' "d
		" Gllog --author=dayong.xie --date=short
	" elseif g:thomas_git_check_uid == 'e' "e
		" Gllog --author=edward.wang --date=short
	" elseif g:thomas_git_check_uid == 'h' "h
		" Gllog --author=jinhaiqing --author=hans.dailybuild --date=short
	" elseif g:thomas_git_check_uid == 'y' "y
		" Gllog --author=Maobiao.Yao --author=YaoMaoBiao --date=short
	" elseif g:thomas_git_check_uid == 't' "t
		" Gllog --author=thomas --author=Thomas\ Chen --date=short
	" elseif g:thomas_git_check_uid == 'z' "z
		" Gllog --author=yue\ zhong --date=short
	" else
		" Gllog --date=short
	" endif
	" End Replaced
	Gllog --author="g:thomas_git_check_uid" --date=short
endfunc

" map <leader>gl :call Thomas_GitCheckFile()<cr>
" Replaced by ThomasChen, From:
" map <leader>gl :exe "R git log --author='yue zhong' ".expand("%")<cr>:vert res 48<cr>:set wfw<cr>:set nonu<cr>:set nornu<cr>:set syntax=git<cr>:set bh=delete<cr><C-w>h<cr>:Gllog --author=yue\ zhong<cr>:redraw!<cr>
" To:
" map <leader>gl :Gllog --author=yue\ zhong --date=short --format='%cd\ %s'<cr>
" map <leader>gl :Gllog --author=yue\ zhong --date=short<cr>
" map <leader>gl :exe "if g:thomas_git_check_uid==0 \| echo 'UID?' \| let g:thomas_git_check_uid=getchar(1) \| endif \| call Thomas_GitCheckFile()"<cr>
map <leader>gl :exe "if g:thomas_git_check_uid==0 \| let g:thomas_git_check_uid=input('UID? ') \| endif \| call Thomas_GitCheckFile()"<cr>
" nnoremap <leader>gl :if g:thomas_git_check_uid==0<cr>:echo "UID?"<cr>:let g:thomas_git_check_uid=getchar()<cr>:endif<cr>call Thomas_GitCheckFile()<cr>
"":redraw!<cr>
" End Replaced
let g:thomas_git_blame_uid=0
func! Thomas_GitBlameFile()
	set scrollbind
	set cursorbind
	" set cursorline
	set scrollopt+=hor
	set nowrap
	Gblame
	normal A
	set scrollbind
	set cursorbind
	set scrollopt+=hor
	set nowrap
	let b:author="thomas"
	if g:thomas_git_blame_uid == 'd' "d
		let b:author="dayong.xie"
	elseif g:thomas_git_blame_uid == 'e' "e
		let b:author="edward.wang"
	elseif g:thomas_git_blame_uid == 'h' "h
		let b:author="jinhaiqing"
		" let b:author="hans.dailybuild"
	elseif g:thomas_git_blame_uid == 'y' "y
		let b:author="Maobiao.Yao"
		" let b:author="YaoMaoBiao"
	elseif g:thomas_git_blame_uid == 't' "t
		let b:author="thomas"
		" let b:author="Thomas\ Chen"
	elseif g:thomas_git_blame_uid == 'z' "z
		let b:author="yue zhong"
	endif
	exe "call matchadd('MarkWord5', '".b:author."', 0x666)"
	let @/=b:author
endfunc

" Replaced by ThomasChen, From:
" map <leader>gb :exe "if g:thomas_git_blame_uid==0 \| let g:thomas_git_blame_uid=input('UID? ') \| endif \| call Thomas_GitBlameFile()"<cr>
" To:
map <leader>gb :exe "let g:thomas_git_blame_uid='t' \| call Thomas_GitBlameFile()"<cr>
" End Replaced

nnoremap <leader>ig :set ignorecase<cr>

map <leader>tc :tabclose<cr>

map <F5> :e %<cr>
nnoremap <silent><leader>s :exe "!stool -t5 ".expand('%').";sleep 1"<cr><cr>
" }}}

" some auto command {{{
"au BufWritePost *.py,*.c,*.cpp,*.h silent! !eval 'echo abc > /tmp/abc.tmp'
autocmd bufenter * if (winnr("$") == 1 && exists("b:NERDTreeType") && b:NERDTreeType == "primary") | q | endif
" augroup NoSimultaneousEdits
" 	autocmd!
" 	autocmd SwapExists * let v:swapchoice = 'o'
" " 	autocmd SwapExists * echomsg 'ErrorMsg'
" " 	autocmd SwapExists * echo 'Duplicate edit session (read only)'
" " 	autocmd SwapExists * echohl None
" augroup END

"au VimEnter * !xmodmap -e 'clear Lock' -e 'keycode 0x42 = Escape'

" 可能导致莫名其妙地进入只读模式。
" au BufWinLeave *.c mkview
" au BufWinEnter *.c silent loadview
" }}}

" location or quickfix window {{{
" Automatically open, but do not go to (if there are errors) the quickfix /
" location list window, or close it when is has become empty.
"
" Note: Must allow nesting of autocmds to enable any customizations for quickfix
" buffers.
" Note: Normally, :cwindow jumps to the quickfix window if the command opens it
" (but not if it's already open). However, as part of the autocmd, this doesn't
" seem to happen.
autocmd QuickFixCmdPost [^l]* nested abo cwindow
autocmd QuickFixCmdPost    l* nested abo lwindow

nnoremap <leader>ln :lnext!<CR>
nnoremap <leader>lp :lprevious!<CR>
nnoremap <leader>cn :cnext!<CR>
nnoremap <leader>cp :cprevious!<CR>
nnoremap <leader>bn :bnext!<CR>
nnoremap <leader>bp :bprevious!<CR>
" }}}

" example of motion function <C-k>{motion} {{{
nmap <silent> <C-k> :set opfunc=CountSpaces<CR>g@
vmap <silent> <C-k> :<C-U>call CountSpaces(visualmode(), 1)<CR>

function! CountSpaces(type, ...)
	let sel_save = &selection
	let &selection = "inclusive"
	let reg_save = @@

	if a:0  " Invoked from Visual mode, use '< and '> marks.
		silent exe "normal! `<" . a:type . "`>y"
	elseif a:type == 'line'
		silent exe "normal! '[V']y"
	elseif a:type == 'block'
		silent exe "normal! `[\<C-V>`]y"
	else
		silent exe "normal! `[v`]y"
	endif

	echomsg strlen(substitute(@@, '[^ ]', '', 'g'))

	let &selection = sel_save
	let @@ = reg_save
endfunction
" }}}


" map <leader>db :D<CR>

" colorscheme ron

endif
" vim:fdm=marker:fdl=0:path=~/.vim/**
